<template>
  <div v-if="type === 'config-mobile' || type === 'mobile'">
    {{ input }}
  </div>
  <div v-if="type === 'config-table' || type === 'table'" class="v-form-item-wrapper">
    {{ input }}
  </div>
</template>

<script setup lang="ts">
import * as utils from './utils'
const { forms, getFormValueList } = inject<{
  forms: any
  getFormValueList: () => []
}>('forms', {
  forms: [],
  getFormValueList: () => {
    return []
  }
})
const emits = defineEmits(['update'])
const props = defineProps<{
  id: string
  tdId: string
  formType: string
  formTypeName: string
  config: any

  type: string // config table mobile print
  formValue: string
}>()
const formValueList = computed<any[]>(() => {
  return getFormValueList ? getFormValueList() : []
})
let oldFormValueList = ref<any[]>([])
const input = ref<string>('')
const onChange = () => {
  emits('update', input.value)
}
const getValue = () => {
  const sourceValue = utils.getSoureValue(props.config.sourceKey, forms.value, formValueList.value)
  return sourceValue ? utils.formatValue(props.config.formatFns, sourceValue) : ''
}
watch(formValueList, async (value: any[]) => {
  const current = value.filter((el: any) => el.key != props.config.key)
  const prev = oldFormValueList.value.filter((el: any) => el.key != props.config.key)
  // 排除本组件的改变
  if (JSON.stringify(current) != JSON.stringify(prev)) {
    input.value = getValue()
    oldFormValueList.value = JSON.parse(JSON.stringify(value))
    onChange()
  }
})
onMounted(() => {
  if (props.type === 'table') {
    oldFormValueList.value = JSON.parse(JSON.stringify(getFormValueList()))
    if (props.formValue) {
      input.value = props.formValue
    } else {
      input.value = getValue()
    }
  }
})
</script>
